package com.housesales.web;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import module.BasicArea;
import module.BasicBanKuai;
import module.Customers;
import module.FavoriteEMPHouses;
import module.HousePhoto;
import module.Houses;
import module.Logs;
import module.NewHouse;
import module.Unit;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import utils.PageUtil;
import bussinessService.basicbussinessService;
import bussinessService.impl.BasicAreaBussinessServiceImpl;
import bussinessService.impl.BasicBanKuaiBussinessServiceImpl;
import bussinessService.impl.FavoriteEMPHousesBussinessServiceImpl;
import bussinessService.impl.NewHouseBussinessServiceImpl;
import bussinessService.impl.UnitBussinessServiceImpl;
import domain.penum.DecorationEnum;
import domain.penum.EstablishmentEnum;
import domain.vo.BlockVO;
import domain.vo.DistrictVO;
import domain.vo.FavoriteQueryObject;
import domain.vo.HouseQueryObject;
import domain.vo.JSONObject;
import domain.vo.Message;
import domain.vo.NewHouseVO;
import domain.vo.UnitVO;

/**
 * 房屋
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/house")
public class HouseController {
	private static final String MODULE = "HOUSE";
	private Logger logger = Logger.getLogger(HouseController.class);

	/**
	 * 房屋业务层实现类
	 */
	private basicbussinessService<NewHouse,NewHouseVO> houseBIS = new NewHouseBussinessServiceImpl();
	/**
	 * 收藏房屋业务实现类
	 */
	private basicbussinessService<FavoriteEMPHouses,NewHouseVO> favoriteBIS = new FavoriteEMPHousesBussinessServiceImpl();
	/**
	 * 行政区业务层实现类
	 */
	private basicbussinessService<BasicArea,DistrictVO> baBSI = new BasicAreaBussinessServiceImpl();
	/**
	 * 小区业务层实现类
	 */
	private basicbussinessService<Unit, UnitVO> unitBIS = new UnitBussinessServiceImpl();
	/**
	 * 板块业务层实现类
	 */
	private basicbussinessService<BasicBanKuai,BlockVO>  blockBSI = new BasicBanKuaiBussinessServiceImpl();
	
	
	/**
	 * 员工集合
	 */
	private List<Houses> housesList = new ArrayList<Houses>();

	/**
	 * 照片
	 */
	private List<HousePhoto> housePhotos;
	/**
	 * 日志
	 */
	private List<Logs> logList;

	@RequestMapping("/add")
	public String addHouses() {
		return "/admin/house/addHouse";
	}

	@RequestMapping("/viewList")
	public ModelAndView viewAllList() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/admin/house/houseList");
		return mv;

	}

	@RequestMapping("/viewListJson")
	public @ResponseBody
	JSONObject<NewHouseVO> viewListJson(
			@RequestParam("page") int page, @RequestParam("rows") int rows,HttpSession session,HouseQueryObject queryObject ) {
		JSONObject<NewHouseVO> json = new JSONObject<NewHouseVO>();
		List<NewHouseVO> vos = new ArrayList<NewHouseVO>();
		try {
			PageUtil.Page(page, rows);
			queryObject.setStart(PageUtil.start);
			queryObject.setEnd(PageUtil.end);
			
			int len = houseBIS.countByQueryObject(queryObject);
			vos = houseBIS.getObjectByQueryObject(queryObject);
			json.setTotal(len);
			json.setRows(vos);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return json;

	}

	
	@RequestMapping("/addNewHouse/{clazz}")
	public @ResponseBody
	Message addNewHouse(@PathVariable("clazz") String clazz,HttpServletRequest request, NewHouse houses,
			Customers custome,@RequestParam("file") MultipartFile file,HttpSession session) {
		Message ms = new Message();
		try {
			String e_sn = session.getAttribute("e_sn").toString();
			String e_name = session.getAttribute("e_name").toString();
			String shopId = session.getAttribute("shopId").toString();
			houses = packageUploadFile(request, file, houses);
			houses.setClazz(NewHouse.CONSTANT_MAP.get(clazz));
			houses.setShop(shopId);
			houses.setE_sn(e_sn);
			houses.setE_name(e_name);
			houses.setCreateTime(new Date());
			String id = request.getParameter("id2");
			if(id != null && !"".equals(id)) {
				houses.setId(Integer.parseInt(id));
			}
			String blockId = request.getParameter("blockId2");
			if(blockId != null && !"".equals(blockId)) {
				houses.setBlockId(Integer.parseInt(blockId));
			}
			houseBIS.merageObject(houses);
		} catch (SQLException e) {
			logger.error(e.getMessage());
			ms.setErrorMsg("房屋基本数据保存失败");
		} catch (IllegalStateException e) {
			logger.error(e.getMessage());
			ms.setErrorMsg("房屋基本数据保存失败");
		} catch (IOException e) {
			logger.error(e.getMessage());
			ms.setErrorMsg("房屋基本数据保存失败");
		}

		return ms;
	}

	@RequestMapping("/modifyNewHouse")
	public @ResponseBody
	Message modifyNewHouse(HttpServletRequest request, NewHouse houses,
			Customers custome,@RequestParam("file") MultipartFile file,HttpSession session) {
		Message ms = new Message();
		try {
			String e_name = session.getAttribute("e_name").toString();
			String shopId = session.getAttribute("shopId").toString();
			houses = packageUploadFile(request, file, houses);
			houses.setShop(shopId);
			String id = request.getParameter("id2");
			if(id != null && !"".equals(id)) {
				houses.setId(Integer.parseInt(id));
			}
			String blockId = request.getParameter("blockId2");
			if(blockId != null && !"".equals(blockId)) {
				houses.setBlockId(Integer.parseInt(blockId));
			}
			NewHouse oldNewHouse = houseBIS.getById(id);
			packageLog(houses, oldNewHouse, e_name);
			houseBIS.merageObject(houses);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			ms.setErrorMsg("房屋基本数据保存失败");
		} catch (IllegalStateException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			ms.setErrorMsg("房屋基本数据保存失败");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			ms.setErrorMsg("房屋基本数据保存失败");
		}

		return ms;
	}
	
	
	
	/**
	 * @throws SQLException 
	 * 
	* @Title: packageLog 
	* @Description: 组装房屋修改记录
	* @param  newHouse    新的数据
	* @param  oldHouse    原有数据
	* @param e_name 用户名
	* @return void    返回类型 
	* @throws
	 */
	private void packageLog(NewHouse newHouse,NewHouse oldHouse,String e_name) throws SQLException{
		Logs logs = new Logs();
		logs.setEmployeeName(e_name);
		logs.setLogDate(new Date());
		logs.setModule(NewHouse.MODULE);
		StringBuilder sb = new StringBuilder();
		//区域
		if(newHouse.getDistrictId() != oldHouse.getDistrictId()){
			BasicArea ba1 = baBSI.getById(Integer.toString(oldHouse.getDistrictId()));
			BasicArea ba2 = baBSI.getById(Integer.toString(newHouse.getDistrictId()));
			sb.append("[");
			sb.append("区域:");
			sb.append((ba1 != null)?ba1.getBhaName():"");
			sb.append("--->");
			sb.append((ba2 != null)?ba2.getBhaName():"");
			sb.append("]");
		}
		//小区
		if(newHouse.getUnitId() != oldHouse.getUnitId()){
			Unit unit1 = unitBIS.getById(Integer.toString(oldHouse.getUnitId()));
			Unit unit2 = unitBIS.getById(Integer.toString(newHouse.getUnitId()));
			sb.append("[");
			sb.append("小区:");
			sb.append((unit1 == null)?"":unit1.getUnitName());
			sb.append("--->");
			sb.append((unit2 == null)?"":unit2.getUnitName());
			sb.append("]");
		}
		
		//车库
		if(newHouse.getBlockId() != oldHouse.getBlockId()){
			BasicBanKuai bbk1 =  blockBSI.getById(Integer.toString(oldHouse.getBlockId()));
			BasicBanKuai bbk2 =  blockBSI.getById(Integer.toString(newHouse.getBlockId()));
			sb.append("[");
			sb.append("板块：");
			sb.append((bbk1 != null)? bbk1.getBb_name():"");
			sb.append("--->");
			sb.append((bbk2 != null)? bbk2.getBb_name():"");
			sb.append("]");
			}
		//地址
		if(!newHouse.getAddress().equals(oldHouse.getAddress())){
			sb.append("[");
			sb.append("地址:");
			sb.append(oldHouse.getAddress());
			sb.append("--->");
			sb.append(newHouse.getAddress());
			sb.append("]");
		}
		//楼层
		if(!newHouse.getFloor().equals(oldHouse.getFloor())){
			sb.append("[");
			sb.append("楼层:");
			sb.append(oldHouse.getFloor());
			sb.append("--->");
			sb.append(newHouse.getFloor());
			sb.append("]");
		}
		//总楼层
		if(!newHouse.getAllfloor().equals(oldHouse.getAllfloor())){
			sb.append("[");
			sb.append("总楼层:");
			sb.append(oldHouse.getAllfloor());
			sb.append("--->");
			sb.append(newHouse.getAllfloor());
			sb.append("]");
		}
		//朝向
		if(!newHouse.getFace().equals(oldHouse.getFace())){
			sb.append("[");
			sb.append("朝向:");
			sb.append(oldHouse.getFace());
			sb.append("--->");
			sb.append(newHouse.getFace());
			sb.append("]");
		}
		//年代
		if(!newHouse.getAge().equals(oldHouse.getAge())){
			sb.append("[");
			sb.append("年代:");
			sb.append(oldHouse.getAge());
			sb.append("--->");
			sb.append(newHouse.getAge());
			sb.append("]");
		}
		//房间
		if(!newHouse.getRoom().equals(oldHouse.getRoom())){
			sb.append("[");
			sb.append("房间:");
			sb.append(oldHouse.getRoom());
			sb.append("--->");
			sb.append(newHouse.getRoom());
			sb.append("]");
		}
		//厅
		if(!newHouse.getTing().equals(oldHouse.getTing())){
			sb.append("[");
			sb.append("厅:");
			sb.append(oldHouse.getTing());
			sb.append("--->");
			sb.append(newHouse.getTing());
			sb.append("]");
		}
		//厨 
		if(!newHouse.getKitchen().equals(oldHouse.getKitchen())){
			sb.append("[");
			sb.append("厨：");
			sb.append(oldHouse.getKitchen());
			sb.append("--->");
			sb.append(newHouse.getKitchen());
			sb.append("]");
		}
		//卫
		if(!newHouse.getWei().equals(oldHouse.getWei())){
			sb.append("[");
			sb.append("卫:");
			sb.append(oldHouse.getWei());
			sb.append("--->");
			sb.append(newHouse.getWei());
			sb.append("]");
		}
		//阳台
		if(!newHouse.getBalcony().equals(oldHouse.getBalcony())){
			sb.append("[");
			sb.append("阳台:");
			sb.append(oldHouse.getBalcony());
			sb.append("--->");
			sb.append(newHouse.getBalcony());
			sb.append("]");
		}
		//装修
		if(!newHouse.getDecoration().equals(oldHouse.getDecoration())){
			sb.append("[");
			sb.append("装修");
			sb.append(DecorationEnum.getName(Integer.parseInt(oldHouse.getDecoration())));
			sb.append("--->");
			sb.append(DecorationEnum.getName(Integer.parseInt(newHouse.getDecoration())));
			sb.append("]");
		}
		//性质
		if(!newHouse.getProperty().equals(oldHouse.getProperty())){
			sb.append("[");
			sb.append("性质");
			sb.append(oldHouse.getProperty());
			sb.append("--->");
			sb.append(newHouse.getProperty());
			sb.append("]");
		}
		//类型
		if(!newHouse.getType().equals(oldHouse.getType())){
			sb.append("[");
			sb.append("类型");
			sb.append(oldHouse.getType());
			sb.append("--->");
			sb.append(newHouse.getType());
			sb.append("]");
		}
		//产权
		if(!newHouse.getOwner().equals(oldHouse.getOwner())){
			sb.append("[");
			sb.append("产权");
			sb.append(oldHouse.getOwner());
			sb.append("--->");
			sb.append(newHouse.getOwner());
			sb.append("]");
		}
		//钥匙
		if(!newHouse.getKeynumber().equals(oldHouse.getKeynumber())){
			sb.append("[");
			sb.append("钥匙：");
			sb.append(oldHouse.getKeynumber());
			sb.append("--->");
			sb.append(newHouse.getKeynumber());
			sb.append("]");
		}
		//建筑面积
		if(!newHouse.getSaleArea().equals(oldHouse.getSaleArea())){
			sb.append("[");
			sb.append("建筑面积：");
			sb.append(oldHouse.getSaleArea());
			sb.append("--->");
			sb.append(newHouse.getSaleArea());
			sb.append("]");
		}
		//来源
		if(!newHouse.getSource().equals(oldHouse.getSource())){
			sb.append("[");
			sb.append("来源：");
			sb.append(oldHouse.getSource());
			sb.append("--->");
			sb.append(newHouse.getSource());
			sb.append("]");
		}
		//结构
		if(!newHouse.getStruct().equals(oldHouse.getStruct())){
			sb.append("[");
			sb.append("结构：");
			sb.append(oldHouse.getStruct());
			sb.append("--->");
			sb.append(newHouse.getStruct());
			sb.append("]");
		}
		//产证
		if(!newHouse.getPremises().equals(oldHouse.getPremises())){
			sb.append("[");
			sb.append("产证：");
			sb.append(oldHouse.getPremises());
			sb.append("--->");
			sb.append(newHouse.getPremises());
			sb.append("]");
		}
		//车库
		if(!newHouse.getGarage().equals(oldHouse.getGarage())){
			sb.append("[");
			sb.append("车库：");
			sb.append(oldHouse.getGarage());
			sb.append("--->");
			sb.append(newHouse.getGarage());
			sb.append("]");
		}
		//使用面积
		if(!newHouse.getActualArea().equals(oldHouse.getActualArea())){
			sb.append("[");
			sb.append("使用面积：");
			sb.append(oldHouse.getActualArea());
			sb.append("--->");
			sb.append(newHouse.getActualArea());
			sb.append("]");
		}
		//设备
		if(!newHouse.getEstablishment().equals(oldHouse.getEstablishment())){
			String[] oldKey = oldHouse.getEstablishment().split(",");
			StringBuffer oldEstablishMent = new StringBuffer();
			for(String key : oldKey) {
				oldEstablishMent.append(EstablishmentEnum.getName(key));
				oldEstablishMent.append(",");
			}
			String[] newKey = newHouse.getEstablishment().split(",");
			StringBuffer newEstablishMent = new StringBuffer();
			for(String key : newKey) {
				newEstablishMent.append(EstablishmentEnum.getName(key));
				newEstablishMent.append(",");
			}
			sb.append("[");
			sb.append("设备");
			sb.append(oldEstablishMent.toString());
			sb.append("--->");
			sb.append(newEstablishMent.toString());
			sb.append("]");
		}
		//备注
		if(!newHouse.getHouseMark().equals(oldHouse.getHouseMark())){
			sb.append("[");
			sb.append("备注：");
			sb.append(oldHouse.getHouseMark());
			sb.append("--->");
			sb.append(newHouse.getHouseMark());
			sb.append("]");
		}
		//总价
		if(!newHouse.getAllprice().equals(oldHouse.getAllprice())){
			sb.append("[");
			sb.append("总价：");
			sb.append(oldHouse.getAllprice());
			sb.append("--->");
			sb.append(newHouse.getAllprice());
			sb.append("]");
		}
		//单价
		if(!newHouse.getUnitprice().equals(oldHouse.getUnitprice())){
			sb.append("[");
			sb.append("单价：");
			sb.append(oldHouse.getUnitprice());
			sb.append("--->");
			sb.append(newHouse.getUnitprice());
			sb.append("]");
		}
		//付款方式
		if(!newHouse.getWay().equals(oldHouse.getWay())){
			sb.append("[");
			sb.append("付款方式：");
			sb.append(oldHouse.getWay());
			sb.append("--->");
			sb.append(newHouse.getWay());
			sb.append("]");
		}
		
		//交付时间
		if(!newHouse.getDeliveryData().equals(oldHouse.getDeliveryData())){
			sb.append("[");
			sb.append("交付时间：");
			sb.append(oldHouse.getDeliveryData());
			sb.append("--->");
			sb.append(newHouse.getDeliveryData());
			sb.append("]");
		}
		//状态
		if(!newHouse.getStatus().equals(oldHouse.getStatus())){
			sb.append("[");
			sb.append("状态：");
			sb.append(oldHouse.getStatus());
			sb.append("--->");
			sb.append(newHouse.getStatus());
			sb.append("]");
		}
		
		//付款条件
		if(!newHouse.getPricecondition().equals(oldHouse.getPricecondition())){
			sb.append("[");
			sb.append("付款条件 ：");
			sb.append(oldHouse.getPricecondition());
			sb.append("--->");
			sb.append(newHouse.getPricecondition());
			sb.append("]");
		}	
		
		//看房方式
		if(!newHouse.getVisit().equals(oldHouse.getVisit())){
			sb.append("[");
			sb.append("看房方式：");
			sb.append(oldHouse.getVisit());
			sb.append("--->");
			sb.append(newHouse.getVisit());
			sb.append("]");
		}		
		
		//看房方式
		if(!newHouse.getVisit().equals(oldHouse.getVisit())){
			sb.append("[");
			sb.append("看房方式：");
			sb.append(oldHouse.getVisit());
			sb.append("--->");
			sb.append(newHouse.getVisit());
			sb.append("]");
		}	
		
		//业主
		if(!newHouse.getOwnerName().equals(oldHouse.getOwnerName())){
			sb.append("[");
			sb.append("业主：");
			sb.append(oldHouse.getOwnerName());
			sb.append("--->");
			sb.append(newHouse.getOwnerName());
			sb.append("]");
		}	
		//业主类型
		if(!newHouse.getOwnerType().equals(oldHouse.getOwnerType())){
			sb.append("[");
			sb.append("业主类型：");
			sb.append(oldHouse.getOwnerType());
			sb.append("--->");
			sb.append(newHouse.getOwnerType());
			sb.append("]");
		}	
		
		//业主电话
		if(!newHouse.getOwnerPhone().equals(oldHouse.getOwnerPhone())){
			sb.append("[");
			sb.append("业主电话：");
			sb.append(oldHouse.getOwnerPhone());
			sb.append("--->");
			sb.append(newHouse.getOwnerPhone());
			sb.append("]");
		}	
		
		//业主备注
		if(!newHouse.getOwnerMark().equals(oldHouse.getOwnerMark())){
			sb.append("[");
			sb.append("业主备注：");
			sb.append(oldHouse.getOwnerMark());
			sb.append("--->");
			sb.append(newHouse.getOwnerMark());
			sb.append("]");
		}	
		if (sb.length() > 0) {
			logs.setLogContent(sb.toString());
			newHouse.getHouseLogs().add(logs);
		}
	}
	/**
	 * 组装文件上传路径
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param file
	 *            上传的文件
	 * @param emp
	 *            组装对象
	 * @return Employees
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	private NewHouse packageUploadFile(HttpServletRequest request,
			MultipartFile file, NewHouse houses) throws IllegalStateException,
			IOException {
		if (!file.isEmpty()) {
			// 当前服务器路径
			StringBuffer uploadPath = new StringBuffer();
			uploadPath.append(request.getSession().getServletContext()
					.getRealPath("/"));
			uploadPath.append("fileupload/");
			uploadPath.append(file.getOriginalFilename());
			File targetFile = new File(uploadPath.toString());
			file.transferTo(targetFile);
			housePhotos = new ArrayList<HousePhoto>();
			HousePhoto hp = new HousePhoto();
			hp.setUrl(file.getOriginalFilename());
			housePhotos.add(hp);
			houses.setHousePhotos(housePhotos);
		}
		return houses;
	}

	@RequestMapping("/{housenumber}")
	public ModelAndView getHouse(@PathVariable("housenumber") String housenumber) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("redirect:viewList.html?msg=''");
		try {
			logger.debug("读取房屋信息");
			NewHouse houses = houseBIS.getById(housenumber);
			mv.addObject("house", houses);
			mv.setViewName("/admin/house/showHouse");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/edit/{housenumber}")
	public ModelAndView editHouse(
			@PathVariable("housenumber") String housenumber) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("redirect:viewList.html?msg=''");
		try {
			logger.debug("编辑房屋信息");
			NewHouse houses = houseBIS.getById(housenumber);
			mv.addObject("house", houses);
			mv.setViewName("/admin/house/editHouse");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mv;
	}

	

	
	
	@RequestMapping("/getAllHouseNumberJson")
	public @ResponseBody JSONObject<NewHouseVO> getAllHouseNumberJson(){
		JSONObject<NewHouseVO>  jsonObject = new JSONObject<NewHouseVO> ();
		List<NewHouseVO> vos = new ArrayList<NewHouseVO>();
		try {
			vos = houseBIS.getAll();
			jsonObject.setTotal(vos.size());
			jsonObject.setRows(vos);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	@RequestMapping("/addFavorite")
	public @ResponseBody Message saveFavorite(@RequestParam("houseId") int houseId,HttpSession session) {
		Message ms = new Message();
		try {
			String e_sn = session.getAttribute("e_sn").toString();
			
			FavoriteQueryObject queryObject = new FavoriteQueryObject();
			queryObject.setE_sn(e_sn);
			queryObject.setHouseId(houseId);
			FavoriteEMPHouses femp = new FavoriteEMPHouses();
			femp.setE_sn(e_sn);
			femp.setHouseId(houseId);
			if(favoriteBIS.countByQueryObject(queryObject) == 0) {
				favoriteBIS.merageObject(femp);
			} else {
				ms.setErrorMsg("改房屋已经被你收藏过了");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			ms.setErrorMsg("收藏失败");
		}
		return ms;
	}
}
